package com.ly.hotel.spainterface.jxd.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.spainterface.NmSwipeCardUtils;
import com.ly.hotel.spainterface.OnSwipeCardInterface;
import com.ly.hotel.spainterface.jxd.activity.JxdXiaoFeiPopupWindow;
import com.ly.hotel.spainterface.nm.bean.NmXFBuyItemBean;
import com.ly.hotel.util.IdChangeUtil;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by SHUBEN on 2018/3/26.
 */

public class JxdXFPopupBuyDialog extends Dialog {
    private JxdXiaoFeiPopupWindow mcontext;
    private List<NmXFBuyItemBean> buylist;
    private TextView totalText;
    private TextView operIntro;
    private TextView firstStep;
    private TextView secondStep;
    private TextView thirdStep;
    private ImageView firstArr;
    private ImageView secondArr;
    private ImageView operImg;
    private TextView closeText;
    private NmSwipeCardUtils swipUtils;
    private Animation alphaAnimation;
    private int stepTag;
    private int countTime = 9;
    private String confirm;
    private boolean needWaiter = false;
    private String keyno;
    private Handler handler;
    private Timer mOffTime;
    private TimerTask tt;

    public JxdXFPopupBuyDialog(JxdXiaoFeiPopupWindow context, int theme) {
        super(context, theme);
        mcontext = context;
        confirm = mcontext.getWaiterConfirm();
    }

    public void initData(List<NmXFBuyItemBean> bl){
        buylist = bl;
        countTime = 9;
        tt = null;
        operIntro.setTextColor(mcontext.getResources().getColor(R.color.white));
        operImg.setVisibility(View.GONE);
        closeText.setVisibility(View.GONE);
        needWaiter = false;
        if(confirm.contains("true")){
            try {
                String money = confirm.split(",")[1];
                double confirmMoney = Double.parseDouble(money);
                if(getTotalManey() > confirmMoney){
                    needWaiter = true;
                }
            }catch (NumberFormatException e){
                e.printStackTrace();
            }
        }
        thirdStep.setVisibility(View.GONE);
        secondArr.setVisibility(View.GONE);

        firstStep.setVisibility(View.VISIBLE);
        secondStep.setVisibility(View.VISIBLE);
        firstArr.setVisibility(View.VISIBLE);
        if(needWaiter){
            thirdStep.setVisibility(View.VISIBLE);
            secondArr.setVisibility(View.VISIBLE);
        }
        initStep();
    }

    //初始化数据和步骤
    private void initStep(){
        totalText.setText(mcontext.getResources().getString(R.string.xf_total_price) + String.format("%.2f",getTotalManey()) + " " + mcontext.getResources().getString(R.string.xf_rmb));
        firstStep.startAnimation(alphaAnimation);
        firstArr.setAlpha(0.2f);
        secondStep.setAlpha(0.2f);
        operIntro.setText(mcontext.getResources().getString(R.string.xf_swipe_confire));
        firstStep.setText("1." + mcontext.getResources().getString(R.string.xf_swipe));
        if(!needWaiter){
            secondStep.setText("2." + mcontext.getResources().getString(R.string.xf_buy_suc));
        }else{
            secondStep.setText("2." + mcontext.getResources().getString(R.string.xf_staff_swipe));
            secondArr.setAlpha(0.2f);
            thirdStep.setAlpha(0.2f);
            thirdStep.setText("3." + mcontext.getResources().getString(R.string.xf_buy_suc));
        }
        stepTag = 1;
        swipUtils.initSwipe();
    }

    private double getTotalManey(){
        double totalPrice = 0.00;
        for(NmXFBuyItemBean ib : buylist){
            double price = ib.getPrice();
            double num = (double) ib.getNum();
            totalPrice += (price*num);
        }
        return totalPrice;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nm_xf_buy_item);
        alphaAnimation = AnimationUtils.loadAnimation(mcontext, R.anim.alpha_anim);

        totalText = findViewById(R.id.xf_total_price);
        operIntro = findViewById(R.id.xf_oper_intro);
        firstStep = findViewById(R.id.xf_first_step);
        secondStep = findViewById(R.id.xf_second_step);
        thirdStep = findViewById(R.id.xf_third_step);
        firstArr = findViewById(R.id.xf_first_arr);
        secondArr = findViewById(R.id.xf_second_arr);
        operImg = findViewById(R.id.xf_oper_img);
        closeText = findViewById(R.id.xf_buy_suc_close);

        Button backBtn = findViewById(R.id.dialog_back);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dismiss();
            }
        });

        swipUtils =  new NmSwipeCardUtils(new OnSwipeCardInterface() {
            @Override
            public void swipeCardListener(String cardId) {
                String newId = cardId.replaceAll("\r\n", "");
                if(newId.length() == 10) {
                    try {
                        long b = Long.parseLong(newId);
                        if(stepTag == 1) {
                            firstStep.clearAnimation();
                            firstStep.setText(mcontext.getResources().getString(R.string.xf_quering));
                            mcontext.requestCard(1,newId);
                        }else{
                            secondStep.clearAnimation();
                            String waiterid = IdChangeUtil.getId(newId,mcontext.getCardtype());
                            secondStep.setText(waiterid);
                            mcontext.requestBuy(buylist,keyno,waiterid);
                        }
                    } catch (NumberFormatException e) {
                        Log.e("swipe", "刷卡含有非法字符，重刷！");
                        swipUtils.initSwipe();
                    }
                }else{
                    Log.e("swipe", "刷卡不足10位，重刷！");
                    swipUtils.initSwipe();
                }
            }
        });

        handler = new Handler(){
            public void handleMessage(Message msg){
                if(msg.what > 0){
                    closeText.setText(mcontext.getResources().getString(R.string.xf_window_close) + " " + msg.what
                            + " " + mcontext.getResources().getString(R.string.xf_time_unit));
                }else{
                    dismiss();
                }
            }
        };

        mOffTime = new Timer(true);
    }

    @Override
    protected void onStop() {
        if(tt != null) {
            tt.cancel();
        }
        swipUtils.setOnSwipeFlag(false);
        super.onStop();
    }

    //收到手牌反馈
    public void onCardBack(int type,boolean tag, String msg){
        if(type == 1) {
            firstStep.setText(msg);
            if (!tag){
                String faildMsg = mcontext.getResources().getString(R.string.xf_buy_faild);
                firstStep.setText(msg);
                secondStep.setText(faildMsg);
                secondStep.setAlpha(1f);
                if(needWaiter){
                    thirdStep.setText(faildMsg);
                    thirdStep.setAlpha(1f);
                }
                operIntro.setTextColor(mcontext.getResources().getColor(R.color.red));
                operIntro.setText(faildMsg + msg);
                operImg.setImageResource(R.drawable.xf_buy_err);
                operImg.setVisibility(View.VISIBLE);
            }else{
                keyno = msg;
                firstStep.setText(mcontext.getResources().getString(R.string.xf_hand_card) + msg);
                if(needWaiter){
                    secondStep.setAlpha(1f);
                    secondStep.startAnimation(alphaAnimation);
                    operIntro.setText(mcontext.getResources().getString(R.string.xf_staff_swipe));
                    stepTag = 2;
                    swipUtils.initSwipe();
                }else {
                    mcontext.requestBuy(buylist,keyno,"admin");
                }
            }
        }
    }

    //收到下单返回
    public void onBuyBack(boolean tag,String msg) {
        operImg.setVisibility(View.VISIBLE);
        if (!tag){
            String faildMsg = mcontext.getResources().getString(R.string.xf_buy_faild);
            operIntro.setTextColor(mcontext.getResources().getColor(R.color.red));
            operIntro.setText(faildMsg + mcontext.getResources().getString(R.string.xf_call_waiter));
            operImg.setImageResource(R.drawable.xf_buy_err);
            if(needWaiter){
                if(!TextUtils.isEmpty(msg)) {
                    secondStep.setText(msg);
                    operIntro.setText(faildMsg + msg);
                }
                thirdStep.setAlpha(1f);
                thirdStep.setText(faildMsg);
            }else {
                if(!TextUtils.isEmpty(msg)) {
                    operIntro.setText(faildMsg + msg);
                }
                secondStep.setAlpha(1f);
                secondStep.setText(faildMsg);
            }
        }else{
            if(needWaiter){
                thirdStep.setAlpha(1f);
                thirdStep.setText(mcontext.getResources().getString(R.string.xf_buy_suc));
            }else {
                secondStep.setAlpha(1f);
                secondStep.setText(mcontext.getResources().getString(R.string.xf_buy_suc));
            }
            operIntro.setText(mcontext.getResources().getString(R.string.xf_buy_suc)+ "！"+
                    mcontext.getResources().getString(R.string.xf_buy_wait));
            operImg.setImageResource(R.drawable.xf_buy_suc);
            showCloseText();
        }
    }

    private void showCloseText(){
        closeText.setVisibility(View.VISIBLE);
        tt = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                handler.sendMessage(msg);
            }
        };
        mOffTime.schedule(tt, 0, 1000);
    }

}